//
//  calenderDetailViewController.m
//  New
//
//  Created by dlios on 15-7-21.
//  Copyright (c) 2015年 yangTao. All rights reserved.
//

#import "calenderDetailViewController.h"

@interface calenderDetailViewController ()

@end

@implementation calenderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[calenderDataBase shareCalenderDataBase]OpenDB];
    [[calenderDataBase shareCalenderDataBase]creatTable];
    
    self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-22-44-49) style:UITableViewStylePlain];
    self.tableV.backgroundColor =[UIColor clearColor];
    [self.view addSubview:self.tableV];
   self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableV.delegate= self;
    self.tableV.dataSource = self;
    
    self.array =[NSMutableArray array];
    
      
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy"];
        NSString *str1 =[NSString stringWithFormat:@"%@",
                         [formatter stringFromDate:date]];
        
        [formatter setDateFormat:@"MM"];
        NSString *string1 =[NSString stringWithFormat:@"%02ld",[[formatter stringFromDate:date]integerValue]];
        
        [formatter setDateFormat:@"dd"];
        NSString *string2 =[NSString stringWithFormat:@"%02ld",[[formatter stringFromDate:date] integerValue]];
    NSString *string3 = [NSString stringWithFormat:@"%02ld",[[formatter stringFromDate:date] integerValue]-1];
    
        self.date = [NSString stringWithFormat:@"%@-%@-%@",str1,string1,string2];
    self.date1 = [NSString stringWithFormat:@"%@-%@-%@",str1,string1,string3];
    
    
//    DateViewController *dateVC = [[DateViewController alloc]init];
//    dateVC.mydelegate = self;
//    
    
//    [self getInFo];
    self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.MBHUD.labelText = @"正在加载中";
    [self.MBHUD show:YES];
    [self.tableV.header beginRefreshing];
    [self headerRefesh];
//    [self footerRefesh];
    [self getInFo];

    
    // Do any additional setup after loading the view.
}
//下拉刷新
-(void)headerRefesh {
    self.tableV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.nextPage = 1;
        self.downUpdata = YES;
        
        //让菊花旋转起来
        self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.MBHUD.labelText = @"正在加载中...";
        [self.MBHUD show:YES];
        [self getInFo];
        
        // 刷新表格
        
        [self.tableV reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        
        
        
    }];
    
}
#warning 上拉加载
//-(void)footerRefesh {
//    
//    self.tableV.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        // 进入刷新状态后会自动调用这个block
//        
//        
//        self.nextPage++;
//        self.downUpdata = NO;
//        self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        self.MBHUD.labelText = @"正在加载中...";
//        [self.MBHUD show:YES];
//        [self getInFo];
//        
//        // 刷新表格
//        [self.tableV reloadData];
//        
//    }];
//    
//    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(TimeAction) userInfo:nil repeats:NO];
//    
//}
//
//-(void)TimeAction{
//
//    [self.tableV.footer endRefreshing];
//    [self.MBHUD hide:YES];
//
//    UIAlertView *alView = [[UIAlertView alloc]initWithTitle:nil message:@"没有更多数据了" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    [alView show];
//    
//}
//

-(void)getInFo{
  
    self.array = [[calenderDataBase shareCalenderDataBase]selectAllCalenderTable];
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = [NSString stringWithFormat:@"http://api.markets.wallstreetcn.com/v1/calendar.json?start=%@&end=%@&_eva_t=1437037990",self.date1,self.date];
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
      
        NSMutableArray *array = [responseObject objectForKey:@"results"];
        if (array.count == 0) {
          
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.tableV.footer endRefreshing];
            [self.tableV.header endRefreshing];
            [self.MBHUD hide:YES];
            UIAlertView *alView = [[UIAlertView alloc]initWithTitle:nil message:@"暂无日程安排" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alView show];
            
        }else{

        [self.array removeAllObjects];
        [[calenderDataBase shareCalenderDataBase]dropTable];
        [[calenderDataBase shareCalenderDataBase]creatTable];
        for (NSMutableDictionary *dic in array) {
            CalenderModel *lalendM = [[CalenderModel alloc]init];
            lalendM.ID = [dic objectForKey:@"id"];
            lalendM.localDateTime = [dic objectForKey:@"localDateTime"];
            lalendM.importance = [dic objectForKey:@"importance"];
            lalendM.title = [dic objectForKey:@"title"];
            lalendM.forecast = [dic objectForKey:@"forecast"];
            lalendM.actual = [dic objectForKey:@"actual"];
            lalendM.previous = [dic objectForKey:@"previous"];
            lalendM.category_id = [dic objectForKey:@"category_id"];
            lalendM.mark = [dic objectForKey:@"mark"];
            lalendM.country = [dic objectForKey:@"country"];
            lalendM.currency = [dic objectForKey:@"currency"];
            lalendM.calendarType = [dic objectForKey:@"calendarType"];
            [[calenderDataBase shareCalenderDataBase] insertNewModel:lalendM];
            [self.array addObject:lalendM];
        }
   }
        [self.tableV reloadData];
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableV.footer endRefreshing];
        [self.tableV.header endRefreshing];
        [self.MBHUD hide:YES];
        
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             NSLog(@"失败==== %@",error);
             // 拿到当前的下拉刷新控件，结束刷新状态
             [self.tableV.footer endRefreshing];
             [self.tableV.header endRefreshing];
             [self.MBHUD hide:YES];
             UIAlertView *alView = [[UIAlertView alloc]initWithTitle:@"网络不给力" message:@"确认您已连接到网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
             [alView show];

             
         }];
    
    
    
}


-(void)bringDate:(NSString *)date andDate1:(NSString *)date1{
   
    [self.array removeAllObjects];
    
    self.array = [[calenderDataBase shareCalenderDataBase]selectAllCalenderTable];
    [self reloadValue];
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = [NSString stringWithFormat:@"http://api.markets.wallstreetcn.com/v1/calendar.json?start=%@&end=%@&_eva_t=1437037990",date,date1];
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
           [self.array removeAllObjects];
        [[calenderDataBase shareCalenderDataBase]dropTable];
        [[calenderDataBase shareCalenderDataBase]creatTable];
        
        NSMutableArray *array = [responseObject objectForKey:@"results"];
        if (array.count == 0) {
           
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.tableV.footer endRefreshing];
            [self.tableV.header endRefreshing];
            [self.MBHUD hide:YES];
            UIAlertView *alView = [[UIAlertView alloc]initWithTitle:nil message:@"暂无日程安排" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alView show];
            
        }else{
        for (NSMutableDictionary *dic in array) {
            CalenderModel *lalendM = [[CalenderModel alloc]init];
            lalendM.ID = [dic objectForKey:@"id"];
            lalendM.localDateTime = [dic objectForKey:@"localDateTime"];
            lalendM.importance = [dic objectForKey:@"importance"];
            lalendM.title = [dic objectForKey:@"title"];
            lalendM.forecast = [dic objectForKey:@"forecast"];
            lalendM.actual = [dic objectForKey:@"actual"];
            lalendM.previous = [dic objectForKey:@"previous"];
            lalendM.category_id = [dic objectForKey:@"category_id"];
            lalendM.mark = [dic objectForKey:@"mark"];
            lalendM.country = [dic objectForKey:@"country"];
            lalendM.currency = [dic objectForKey:@"currency"];
            lalendM.calendarType = [dic objectForKey:@"calendarType"];
            [self.array addObject:lalendM];
          
        }
          [self.tableV reloadData];
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.tableV.footer endRefreshing];
            [self.tableV.header endRefreshing];
            [self.MBHUD hide:YES];
        
      
        
        }
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             NSLog(@"失败==== %@",error);
             // 拿到当前的下拉刷新控件，结束刷新状态
             [self.tableV.footer endRefreshing];
             [self.tableV.header endRefreshing];
             [self.MBHUD hide:YES];
             UIAlertView *alView = [[UIAlertView alloc]initWithTitle:@"网络不给力" message:@"确认您已连接到网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
             [alView show];
         }];
    

    

}

-(void)reloadValue {
    self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.MBHUD.labelText = @"正在加载中...";
    [self.MBHUD show:YES];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.array.count;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *ident = @"cell";
    calenderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (cell== nil) {
        cell = [[calenderDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    cell.calenMod =[self.array objectAtIndex:indexPath.row];
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 130;

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
